package com.nononsenseapps.feeder.ui.feed

import android.content.Context
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.nononsenseapps.feeder.db.room.FeedItemDao
import com.nononsenseapps.feeder.db.room.ID_UNSET
import com.nononsenseapps.feeder.db.view.PreviewItem
import com.nononsenseapps.feeder.ui.base.PreviewItemDiffer
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.DateTimeFormatter
import java.util.Locale


class FeedItemListAdapter(private val context: Context, private val itemDao: FeedItemDao, val viewModel:Boolean = false, private val actionCallback: ActionCallback) :
        ListAdapter<PreviewItem, RecyclerView.ViewHolder>( PreviewItemDiffer) {

    val feedItemListAdapterHelper = FeedItemListAdapterHelper(this,context,itemDao,viewModel,actionCallback)

    private val shortDateTimeFormat: DateTimeFormatter =
            DateTimeFormat.mediumDate().withLocale(Locale.getDefault())


    init {
        setHasStableIds(true)
    }

    override fun getItemId(position: Int): Long {
        return getItem(position)?.id ?: ID_UNSET
    }

    override fun getItem(position: Int): PreviewItem? {
        return super.getItem(feedItemListAdapterHelper.getItemPosition(position))
    }

    override fun getItemViewType(position: Int): Int {
        return feedItemListAdapterHelper.getItemViewType(getItem(position),position = position)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return feedItemListAdapterHelper.onCreateViewHolder(parent,viewType)
    }

    override fun onViewRecycled(holder: RecyclerView.ViewHolder) {
       super.onViewRecycled(holder)
       if(holder is FeedItemHolder){
           holder.clearHolder()
       }
    }

    override fun onBindViewHolder(vHolder: RecyclerView.ViewHolder, position: Int) {
        feedItemListAdapterHelper.onBindViewHolder(vHolder=vHolder, position = position, item = getItem(position))
    }

    fun clearItems() {
        super.submitList(null)
    }

    fun setShadowAble(shadowAble:Boolean=true){
        feedItemListAdapterHelper.shadowAble=shadowAble
    }
}
